﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using DocumentGain.model;
using DocumentGain;
using DocumentGain.dal;
using System.Configuration;
using System.Threading;
using Ican.YunPan.Services;
using Ican.YunPan.Services.GridFS;

namespace DocumentGain
{
    public partial class Leading_Message数据补充 : Form
    {
        string connstr = ConfigurationManager.AppSettings["MongoConnectionString"];
        string dbName = ConfigurationManager.AppSettings["MongoDBName"];
        string FilePath = ConfigurationManager.AppSettings["FilePath"];

        string cutTime = ConfigurationManager.AppSettings["cutTime"];
        string iscutTimebefore = ConfigurationManager.AppSettings["iscutTimebefore"];


        private delegate void SetControlTextCallback(Control o, string text);
        Service service = new Service();
        private string _allmessage = "";
        string LogDate = "";

        string nr = "";

        public void DataLeadingin(object o)
        {
            MessageShow("开始导入Message补充");
            string sql = @"select Id,InstanceId,TableName,Title,updatetime,ParticipantsId,ParticipantsInfo from View_WorkFlow_Sc where InstanceId not in (select InstanceId from mp_message)";
            DataTable dt = sqlHelpIcanYunPan.Query(sql).Tables[0];
            WriteLogFile("有" + dt.Rows.Count+"条数据待导入");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                MessageShow("开始导入" + i.ToString() + "条数据");
                MP_Message mp_message = new MP_Message();
                mp_message.Id = Guid.NewGuid();
                mp_message.MsgType = "WorkFlow";
                mp_message.Status = "2";
                mp_message.Title = dt.Rows[i]["Title"].ToString();
                mp_message.CurrParticipants = "[]";
                mp_message.InstanceId = dt.Rows[i]["InstanceId"].ToString();
                mp_message.AppId = "a1ea0f79-00c4-46b3-8229-182e022da948";
                mp_message.AppName = "地铁项目_SC";
                mp_message.FormCode = dt.Rows[i]["TableName"].ToString();
                mp_message.CreatedDate = Convert.ToDateTime(dt.Rows[i]["updatetime"].ToString());
                mp_message.UpdatedDate = Convert.ToDateTime(dt.Rows[i]["updatetime"].ToString());
                string SequenceNo = "SCT_"+mp_message.FormCode + DateTime.Now.ToString("yyyyMMddHHmmss") + i.ToString();
                try
                {
                    string sql2 = @"select ID,Name from YP_User where  ID = '" + dt.Rows[i]["ParticipantsId"].ToString() + "'";
                    DataTable dt2 = sqlHelpIcanYunPan.Query(sql2).Tables[0];
                    mp_message.UserId = dt2.Rows[0]["ID"].ToString();
                    mp_message.UserName = dt2.Rows[0]["Name"].ToString();
                    mp_message.ParticipantsId = dt2.Rows[0]["ID"].ToString();
                }
                catch
                {
                    mp_message.UserId = dt.Rows[i]["ParticipantsId"].ToString();
                    mp_message.UserName = dt.Rows[i]["ParticipantsInfo"].ToString();
                }

                try
                {
                    string sql3 = @"select qicaorq,flowtype from [10.104.12.1].Document.dbo.MainDocument where DocumentID in (select DocumentID from MP_DocumentID where InstanceId = '" + mp_message.InstanceId + "')";
                    DataTable dt3 = sqlHelpIcanYunPan.Query(sql3).Tables[0];
                    mp_message.WorkflowTitle = dt3.Rows[0]["flowtype"].ToString();

                    string sql4 = "select WorkflowName,WorkflowPackage,MPListId from [dbo].[FlowTypeCorrelation] where flowtype = '" + mp_message.WorkflowTitle + "'";
                    DataTable dt4 = sqlHelp.Query(sql4).Tables[0];
                    mp_message.MPListId = dt4.Rows[0]["MPListId"].ToString();
                    mp_message.WorkflowName = dt4.Rows[0]["WorkflowName"].ToString();
                    mp_message.PackageName = dt4.Rows[0]["WorkflowPackage"].ToString();
                }
                catch
                {
                    mp_message.WorkflowTitle = "";
                    mp_message.MPListId = "";
                }
                mp_message.FormDataId = dt.Rows[i]["Id"].ToString();
                mp_message.WFStatus = 2;
                mp_message.Contents = mp_message.UserName + "在" + mp_message.CreatedDate + "发起了【" + mp_message.WorkflowTitle + "】的流程，流程编号为：【" + SequenceNo + "】";
                
                service.AddMessage(mp_message);
                
            }
            sql = @"update MP_Message set AttachmentIds = 1 from WHRT_Attachment where MP_Message.InstanceId = WHRT_Attachment.pid";
            sqlHelpIcanYunPan.ExecuteSql(sql);

            MessageShow("导入完成");
        }

        public Leading_Message数据补充()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(DataLeadingin);
        }



        public void MessageShow(String input)
        {
            SetControlText(this.textBox1, input);
        }

        //写入文本日志
        public void WriteLogFile(String input)
        {
            SetControlText(this.textBox1, input);

            //指定日志文件的目录
            string fname = ConfigurationManager.AppSettings["LogPath"];

            //定义文件信息对象 
            FileInfo finfo = new FileInfo(fname + "Leading_PublicDoc" + DateTime.Now.ToString("yyyyMMdd") + ".txt");

            //判断文件是否存在以及是否大于2K 
            if (finfo.Exists && finfo.Length > 20480000)
            {
                //删除该文件 
                finfo.Delete();
            }
            //创建只写文件流 
            using (FileStream fs = finfo.OpenWrite())
            {
                //根据上面创建的文件流创建写数据流 
                StreamWriter w = new StreamWriter(fs);
                //设置写数据流的起始位置为文件流的末尾 
                w.BaseStream.Seek(0, SeekOrigin.End);

                w.Write("\r\n ");

                //写入日志内容并换行 
                w.Write(input + "\n ");
                //w.Write("--\n ");
                //清空缓冲区内容，并把缓冲区内容写入基础流 
                w.Flush();
                //关闭写数据流 
                w.Close();
            }
        }
        private void SetControlText(Control o, string text)
        {
            try
            {
                if (o.InvokeRequired)
                {
                    SetControlTextCallback d = new SetControlTextCallback(SetControlText);
                    this.Invoke(d, o, text);
                }
                else
                {
                    _allmessage = text + "\r\n" + _allmessage;
                    o.Text = _allmessage;
                }
            }
            catch { }
        }


        public void DataLeadingin2(object o)
        {

//            select distinct MP_Message.UserId, MP_Message.ParticipantsId,MP_Message.UserName,View_WorkFlow_Sc.ParticipantsId,View_WorkFlow_Sc.ParticipantsInfo
//from MP_Message,View_WorkFlow_Sc
//where MP_Message.id not in (
//select ID from MP_Message where UserId != '' and ParticipantsId != '' and ParticipantsId != '' and UserName != '') 
//and MP_Message.InstanceId = View_WorkFlow_Sc.InstanceId
//and MP_Message.UserName = View_WorkFlow_Sc.ParticipantsInfo

            MessageShow("开始导入用户或部门补充数据");
            string sql = @"select id,UserId,ParticipantsId,UserName from MP_Message 
where id not in (
select ID from MP_Message where UserId != '' and ParticipantsId != '' and ParticipantsId != '' and UserName != '')";
            DataTable dt = sqlHelpIcanYunPan.Query(sql).Tables[0];
            WriteLogFile("有" + dt.Rows.Count + "条数据待导入");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                MessageShow("开始导入" + i.ToString() + "条数据");
                string id = dt.Rows[i]["id"].ToString();
                string UserId = dt.Rows[i]["UserId"].ToString();
                string ParticipantsId = dt.Rows[i]["ParticipantsId"].ToString();
                string UserName = dt.Rows[i]["UserName"].ToString().Replace("微软需求_", "");

                if (UserId != "")
                {
                    string sql1 = @"select YP_Org.ID as OrgId,YP_Org.Name as OrgName,YP_User.Id as UserId,YP_User.Name as UserName from YP_User,YP_Org where YP_User.SourceParentID = YP_Org.ID and YP_User.Id = '" + UserId + "'";
                    DataTable dt1 = sqlHelpIcanYunPan.Query(sql1).Tables[0];
                    if (dt1.Rows.Count > 0)
                    {
                        string sqlupdate = "update MP_Message set ParticipantsId = '" + dt1.Rows[0]["UserId"].ToString() + "',UserName = '" + dt1.Rows[0]["UserName"].ToString() + "' where id = '" + id + "'";
                        sqlHelpIcanYunPan.ExecuteSql(sqlupdate);
                    }
                }
                else if (ParticipantsId != "")
                {
                    string sql4 = @"select ID,Name from YP_User where Id = '" + ParticipantsId + "'";
                    DataTable dt4 = sqlHelpIcanYunPan.Query(sql4).Tables[0];
                    if (dt4.Rows.Count == 1)
                    {
                        string sqlupdate = "update MP_Message set UserId = '" + dt4.Rows[0]["ID"].ToString() + "',UserName = '" + dt4.Rows[0]["Name"].ToString() + "' where id = '" + id + "'";
                        sqlHelpIcanYunPan.ExecuteSql(sqlupdate);
                    }
                }
                else if (UserName != "")
                {
                    string sql2 = @"select YP_Org.ID as OrgId,YP_Org.Name as OrgName,YP_User.Id as UserId,YP_User.Name as UserName 
from YP_User,YP_Org where YP_User.SourceParentID = YP_Org.ID 
and YP_User.Alias in (
select LoginName from [dbo].[UserRelation] where UserName = '" + UserName + "')";
                    DataTable dt2 = sqlHelpIcanYunPan.Query(sql2).Tables[0];
                    if (dt2.Rows.Count == 1)
                    {
                        string sqlupdate = "update MP_Message set UserId = '" + dt2.Rows[0]["UserId"].ToString() + "',ParticipantsId = '" + dt2.Rows[0]["UserId"].ToString() + "' where id = '" + id + "'";
                        sqlHelpIcanYunPan.ExecuteSql(sqlupdate);
                    }

                    string sql3 = @"select ID,Name from YP_User where Name = '" + UserName + "'";
                    DataTable dt3 = sqlHelpIcanYunPan.Query(sql3).Tables[0];
                    if (dt3.Rows.Count == 1)
                    {
                        string sqlupdate = "update MP_Message set UserId = '" + dt3.Rows[0]["ID"].ToString() + "',ParticipantsId = '" + dt3.Rows[0]["ID"].ToString() + "' where id = '" + id + "'";
                        sqlHelpIcanYunPan.ExecuteSql(sqlupdate);
                    }
                }
            }
            MessageShow("导入完成");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(DataLeadingin2);
        }

    }
}
